import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import {
    allRoutes
} from '@/config'
import iView from 'iview';
import store from '@/store'

var routes = []

allRoutes.forEach(r => {
    //生成一级路由
    var obj = {
        path: r.path,
        meta: {
            title: r.label
        },
        children: [],
        component: () => import("@/views/" + r.component)
    }
    routes.push(obj)
    //生成二级路由
    if (r.sublist) {
        r.sublist.forEach(rr => {
            obj.children.push({
                path: rr.path,
                meta: {
                    title: r.label + "-" + rr.label
                },
                component: () => import("@/views/" + rr.component)
            })
        })
    }
});

routes.push({
    path: "*",
    component: () => import("@/views/system/404.vue")
})

const router = new VueRouter({
    routes
})

router.beforeEach((to, from, next) => {

    //需要判断是否登录的页面
    if (to.meta && to.meta.auth) {
        if (!store.getters.getNickName) {
            next("/login")
        } else {
            iView.LoadingBar.start();
            if (to.meta && to.meta.title)
                document.title = to.meta.title
            next()
        }
    } else {
        iView.LoadingBar.start();
        if (to.meta && to.meta.title)
            document.title = to.meta.title
        next()
    }
})

router.afterEach((to, from) => {
    iView.LoadingBar.finish();
    allRoutes.forEach((r, i) => {
        if (r.sublist) {
            r.sublist.forEach((rr, j) => {
                if (rr.path === to.path) {
                    store.commit("setActiveId", {
                        menuid: (i + 1).toString(),
                        labelid: i + 1 + "-" + (j + 1)
                    });
                }
            });
        }
    });

});


export default router